//
//  ZCCommentDetailsVC.m
//  zctx
//
//  Created by apple on 15/12/30.
//  Copyright © 2015年 sanliang. All rights reserved.
//

#import "ZCCommentDetailsVC.h"
#import "ZCCommentDetailsCell.h"
#import "HcCustomKeyboard.h"
#import "ZCLoginVC.h"
@interface ZCCommentDetailsVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,HcCustomKeyboardDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)UITextField *mTextView;
@property (nonatomic,assign)NSInteger offset;
@end

@implementation ZCCommentDetailsVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ZCCommentDetailsVC"];
    [MTA trackPageViewBegin:@"ZCCommentDetailsVC"];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ZCCommentDetailsVC"];
    [MTA trackPageViewEnd:@"ZCCommentDetailsVC"];
    self.tabBarController.hidesBottomBarWhenPushed = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initnavegation];
    self.navigationItem.title = @"详情";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.dataArray = [[NSMutableArray alloc]init];
    _offset = 0;
    NSLog(@"self.comment = %@ %ld",self.comments,self.isarticles);
    //个人信息请求
    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
//    });
    
    
    [self initTableView]; //初始化UITableView
    [self requestData];
    [self initFooterView];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCCommentDetailsCell" bundle:nil] forCellReuseIdentifier:@"commentDetailsCell"];
    self.tableView.mj_footer = [MJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

#pragma mark 加载更多
-(void)loadMoreData{
    //上拉加载
    _offset = _offset+1;
    [self requestData];
}

-(void)requestData{
    if (_offset==0) {
        [GMDCircleLoader setOnView:self.view withTitle:@"努力加载中..." animated:YES];
        [self.dataArray removeAllObjects];
    }
    if (self.isarticles == 1) {
        NSString *ctype = nil;
        if ([self.isweekly isEqualToString:@"1"]) {
            ctype = @"6";
        }else{
            ctype = @"2";
        }
        [NetworkManager requestIndexGetAddarticleCommentslikeWithNewscid:self.comments.forId mid:UserModel.mid password:UserModel.password pagecount:[NSString stringWithFormat:@"%ld",(long)_offset] pid:self.comments.hotCommentsIdentifier   ctype:ctype success:^(NSDictionary *dictResponse) {
            [self.tableView.mj_footer endRefreshing];
            [GMDCircleLoader hideFromView:self.view animated:YES];
            NSObject *dict =(NSObject *)[dictResponse objectForKey:@"content"];
            if ([dict isKindOfClass:[NSArray class]]) {
                NSArray *array  = (NSArray *)dict;
                if (array.count>0) {
                    for (NSDictionary *dict in array) {
                        ZCInvolvedDetailsModelHotComments *model = [ZCInvolvedDetailsModelHotComments modelObjectWithDictionary:dict];
                        [self.dataArray addObject:model];
                        NSLog(@"self.dataARRAY = %@",self.dataArray);
                    }
                    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
                }
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        } failure:^(NSError *error) {
        }];
    }else{
        [NetworkManager requestFoundingGetOnecommentsWithId:self.pid Mid:UserModel.mid password:UserModel.password pagecount:[NSString stringWithFormat:@"%ld",(long)_offset] pid:self.comments.hotCommentsIdentifier success:^(NSDictionary *dictResponse) {
            [self.tableView.mj_footer endRefreshing];
            [GMDCircleLoader hideFromView:self.view animated:YES];
            NSObject *dict =(NSObject *)[dictResponse objectForKey:@"content"];
            if ([dict isKindOfClass:[NSArray class]]) {
                NSArray *array  = (NSArray *)dict;
                if (array.count>0) {
                    for (NSDictionary *dict in array) {
                        ZCInvolvedDetailsModelHotComments *model = [ZCInvolvedDetailsModelHotComments modelObjectWithDictionary:dict];
                        [self.dataArray addObject:model];
                        NSLog(@"self.dataARRAY = %@",self.dataArray);
                    }
                    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
                }
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        } failure:^(NSError *error) {
            [GMDCircleLoader hideFromView:self.view animated:YES];
        }];
    }
}

-(void)initFooterView{
    UIView *footer = [[UIView alloc]init];
   footer.backgroundColor = [UIColor colorWithHexString:@"#F4F5F7"];
    [self.view addSubview:footer];
    [footer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.bottom).with.offset(0);
        make.height.mas_equalTo(@(44));
        make.right.equalTo(self.view.right).with.offset(0);
        make.left.equalTo(self.view.left).with.offset(0);
    }];
    self.mTextView =[[UITextField alloc]init];
    [footer addSubview:self.mTextView];
    [self.mTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(footer.centerY);
        make.height.mas_equalTo(@(32));
        make.right.equalTo(footer.right).with.offset(-15);
        make.left.equalTo(footer.left).with.offset(15);
    }];
    self.mTextView.font = [UIFont systemFontOfSize:15];
    self.mTextView.backgroundColor =[UIColor whiteColor];
    self.mTextView.delegate = self;
    self.mTextView.placeholder = @"我来说两句";
    self.mTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    self.mTextView.layer.cornerRadius = 5;
    self.mTextView.layer.borderWidth = 0.6;
    self.mTextView.layer.borderColor = RGB(236, 237, 238).CGColor;
    footer.layer.borderWidth =1;
    footer.layer.borderColor = RGB(236, 237, 238).CGColor;
}

#pragma mark 导航栏
-(void)initnavegation{
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = barButtonItem_leftNavBar;
}

-(void)backButtonPressed{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)initTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.sectionFooterHeight = 0.0001;
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"#fafcfb"];
    self.tableView.separatorColor = RGB(236, 237, 238);
    
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0,44, 0));
    }];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }else{
        if (self.dataArray.count>0) {
            return self.dataArray.count;
        }else{
            return 0;
        }
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *IDcell = @"commentDetailsCell";
    ZCCommentDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:IDcell];
    if (!cell) {
        cell = [[ZCCommentDetailsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:IDcell];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section ==0) {
        cell.index = indexPath;
        cell.model = self.comments;
        return cell;
    }else{
        cell.index = indexPath;
        cell.model = self.dataArray[indexPath.row];
        return cell;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZCInvolvedDetailsModelHotComments *model;
    if (indexPath.section==0) {
        model = self.comments;
    }else{
        model =self.dataArray[indexPath.row];
    }
//    NSLog(@"model = %@",model);
    NSString *reuseIdentifier = @"commentDetailsCell";
    ZCCommentDetailsCell *cell = [self.tableView dequeueReusableCellWithIdentifier:  reuseIdentifier];
    [cell.contentLable setText:model.content];

    [cell setNeedsUpdateConstraints];
    [cell updateConstraintsIfNeeded];
    // 得到cell的contentView需要的真实高度
    CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    
//    NSLog(@"heithy = %f",height);
    // 要为cell的分割线加上额外的1pt高度。因为分隔线是被加在cell底边和contentView底边之间的。
    height +=1.0f;
    return height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, 10)];
    return headView;
}

-(void)likeButtonClickindex:(NSIndexPath *)indexPath{
    
}
-(void)commentButtonClickindex:(NSIndexPath *)indexPath{
    
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    NSLog(@"sdfa");
    if (UserModel.password.length>1) {
        [[HcCustomKeyboard customKeyboard]textViewShowView:self customKeyboardDelegate:self andType:HcCustomKeyboardTypeTextfield andplaceholder:@"我来说两句"];
        
    }else{
        [textField resignFirstResponder];
        ZCLoginVC *loginVC = [[ZCLoginVC alloc]init];
        loginVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}
-(void)talkBtnClick:(UITextView *)textViewGet
{
    
    NSLog(@"hhhhhhhhh");
    if (self.isarticles ==1) {
        NSString *ctype = nil;
        if ([self.isweekly isEqualToString:@"1"]) {
            ctype = @"6";
        }else{
            ctype = @"2";
        }
        [NetworkManager requestIndexGetAddarticleWithNewsid:self.comments.forId mid:UserModel.mid password:UserModel.password content:textViewGet.text pid:self.comments.hotCommentsIdentifier ctype:ctype success:^(NSDictionary *dictResponse) {
            NSString *err = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"err"]];
            if ([err isEqualToString:@"0"]) {
                [[[iToast makeText:@"评论成功"]setGravity:iToastGravityCenter] show];
                [self requestData];
            }else{
                [[[iToast makeText:@"评论失败"]setGravity:iToastGravityCenter] show];
            }
        } failure:^(NSError *error) {
            
        }];
    }else{
        [NetworkManager requestFoundingGetOnecommentWithId:self.comments.forId Mid:UserModel.mid password:UserModel.password content:textViewGet.text pid:self.comments.hotCommentsIdentifier success:^(NSDictionary *dictResponse) {
            NSString *err = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"err"]];
            if ([err isEqualToString:@"0"]) {
                [[[iToast makeText:@"评论成功"]setGravity:iToastGravityCenter] show];
                [self requestData];
            }else{
                [[[iToast makeText:@"评论失败"]setGravity:iToastGravityCenter] show];
            }
        } failure:^(NSError *error) {
        }];
    }
}


@end
